<?php
/**
 * Created by PhpStorm.
 * User: hgs
 * Date: 16/4/7
 * Time: 下午3:16
 */

namespace work {

	use C\ctr;
    use C\lib\Ditu;
    use C\lib\Session;
	use C\mod\city;
	use C\mod\address;
	use C\mod\com;
	use C\mod\comPhone;
	use C\mod\coupon;
    use C\mod\express;
    use C\mod\order;
	use C\lib\Db;
	use C\mod\orderPiece;
	use C\lib\Sql;
	use C\mod\user;
    use C\mod\bill;
    use C\mod\feedback;
    use C\lib\Wxpay;
    use C\lib\Wxapi;
    use C\mod\code;
    use C\mod\worker;
    use C\mod\workerd;

    class bpost extends ctr {

		function __construct() { //定义构造函数
			Db::connect();
		}
		public function main() {

			Session::start(); // echo 220;
            //$_SESSION=[];
//var_dump($_SESSION);exit;
			// --- 加载成功的话可能会有如下可能 ---
			// --- 已经成功登录/微信成功登录/---
			if(isset($_SESSION['user.id']) && isset($_SESSION['user.wx_openid'])) {
                //跳转至首页
                $this->success();
			} else {
                $_SESSION['location']='http://s.biandikeji.com/work/bpost/main';
			    //echo 33;exit;
				// 跳转到登录页面
                header('Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx08a944d5a385e626&redirect_uri=' . urlencode(HTTP_PATH . 'work/buser/weixin') . '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect');
			}

		}


		// --- 首页页面显示我的快递信息 ---

		public function success() {
		    Session::start();
		    //var_dump($_SESSION);exit;
		    Db::connect();
		    if(isset($_SESSION['user.id'])){
                $list= [];
                $data=order::getList(['user_id'=>$_SESSION['user.id'],['type','!=',0],'state'=>2,['time_add','>=',$_SERVER['REQUEST_TIME']-60*60*24*60]],[0,10],['id','DESC']);
                foreach ($data as $value){
                    $state=$this->getState($value->express_name,$value->ex_order);
//                    if($state==1){
//                            $s = '已签收';
//                    }else if($state==0){
//                        $s = '运输中';
//                    }else{
//                        $s = '异常单';
//                    }
                    if($state==2){
                        $s = '异常单';
                    }else{
                        $first=str_replace('[','',$state['context']);
                        $s = str_replace(']','',$first);
                    }
                    $list[] =[
                        'id'=>$value->id,
                        'express_name' => $value->express_name,
                        'ex_order' => $value->ex_order,
                        'time' => $state['time'],
                        'state' => $s
                    ];
                }

                //var_dump($arr);exit;
                //$count=count(order::getList(['user_id'=>$_SESSION['user.id']]));
                //分页
//                $pagesize=10;
//                $totalpage=ceil($count/$pagesize);
                //var_dump($count);exit;
//                if($count>0){
//                    if (isset($_POST['page'])) {
//                        $page = $_POST['page'] + 0;
//                        if($page<0){
//                            $page=1;
//                        }elseif ($page>$totalpage){
//                            $page=$totalpage;
//                        }
//                    } else {
//                        $page = 1;
//                    }
//                    $data=order::getList(['user_id'=>$_SESSION['user.id']],[($page - 1) * $pagesize, $pagesize],['id','DESC']);
//                    //select name,submittime from enterprise where submittime between date_sub(now(),interval 6 month) and now();
//                    $all=Db::query('select ex_order,express_name,time_add from bd_order WHERE time_add between date_sub(now(),interval 2 month) and now() and user_id='.$_SESSION['user.id']);
//                    //var_dump($all);exit;
//                    $data = $all->fetch(\PDO::FETCH_ASSOC);
//                    //var_dump($data);exit;
//                    foreach ($data as $value){
//                        $list[] = [
//                            'ex_order' => $value->ex_order,
//                            'express_name' => $value->express_name,
//                            'time_add' => date("Y-m-d",$value->time_add)
//                        ];
//
//                        $state=$this->getState($value->express_name,$value->ex_order);
//                        if($state==1){
//                            $states[]['state']='已签收';
//                        }else{
//                            $states[]['state']='运输中';
//                        }
//
//                    }
//                    foreach ($list as $k=>$r){
//                        $arr[] = array_merge($r,$states[$k]);
//                    }
//                }
                $express=$this->allExpress();
               // var_dump($express);exit;
                $this->loadView('bdkd/home/main',['list'=>$list,'express'=>$express]);
            }else{
		        $user=user::get(['wx_openid'=>$_SESSION['user.wx_openid']]);
		        if($user){
                    $_SESSION['user.id']=$user->id;
                }else{
                    $this->loadView('bdkd/sign/main');
                }
            }
		}


		//邀请码页面
		public function code(){
            Session::start();
            if(isset($_SESSION['user.id'])){
                $this->loadView("bdkd/user/yaoqing");
            }else{
                $this->loadView('bdkd/sign/main');
            }
        }

        //-成长历程里面显示--
        public function group(){
            Session::start();
            if(isset($_SESSION['user.id'])){
                $this->loadView("bdkd/group/group");
            }else{
                //调到入口文件
                header('Location: http://s.biandikeji.com/work/bpost/main');
            }

        }
        //---显示所有的快递公司---
        public function allExpress(){
		    $data= [];
		    $data=express::getList(['available'=>1]);
		    //var_dump($data);exit;
		    return $data;
        }
/*
 * 测试 物流
 */
public function x(){
    $type='yunda';
    $postid=3964430724979;
    $url = "http://www.kuaidi100.com/query?type=$type&postid=$postid&id=19&valicode=&temp=".mt_getrandmax();
    $express = json_decode(self::getExpressMsg($url) ,true);

    //print_r($express);exit;
    if(isset($express['message']) && ($express['message'] === 'ok')) {
        if($express['state']==3){
            $data=[
                'state'=>'已签收',
                'code'=>$type,
                'ex_order'=>$postid,
                'list'=>$express['data']
            ];
        }else if($express['state']==2 || $express['state']==6){
            $data=[
                'state'=>'运输中',
                'code'=>$type,
                'ex_order'=>$postid,
                'list'=>$express['data']
            ];
        }else{
            $data=[
                'code'=>$type,
                'ex_order'=>$postid,
                'state'=>'异常单',
            ];
        }
    }else{
        $data=[
            'code'=>$type,
            'ex_order'=>$postid,
            'state'=>'异常单',
        ];
    }
    print_r($data);exit;
}

		//---查询物流信息---
        public function goodsInfo(){
            Session::start();
		    if(isset($_SESSION['user.id'])){

                if(!empty($_GET['code'])){

                    $type=$_GET['code'];
                }else{
                    $this->success();
             
                }
                if(!empty($_GET['ex_order'])){

                    $postid=$_GET['ex_order'];
                }else{
                    $this->success();
                }

                $user=user::get(['id'=>$_SESSION['user.id']]);
                $url = "http://www.kuaidi100.com/query?type=$type&postid=$postid&id=19&valicode=&temp=".mt_getrandmax();
                $express = json_decode(self::getExpressMsg($url) ,true);
              // print_r($express);exit;

                if(isset($express['message']) && ($express['message'] === 'ok')) {
                    if($express['state']==3){
                        $data=[
                            'path'=>$user->path,
                            'state'=>'已签收',
                            'code'=>$type,
                            'ex_order'=>$postid,
                            'list'=>$express['data']
                        ];
                    }else if($express['state']==2 || $express['state']==6){
                        $data=[
                            'path'=>$user->path,
                            'state'=>'异常单',
                            'code'=>$type,
                            'ex_order'=>$postid,
                            'list'=>$express['data']
                        ];
                    }else{
                        $data=[
                            'path'=>$user->path,
                            'code'=>$type,
                            'ex_order'=>$postid,
                            'state'=>'运输中',
                            'list'=>$express['data']
                        ];
                    }
                }else{
                    $data=[
                        'path'=>$user->path,
                        'code'=>$type,
                        'ex_order'=>$postid,
                        'state'=>'异常单',
                        'list'=>""
                    ];
                }
                $this->loadView('bdkd/home/details',['info'=>$data]);
            }else
                $this->loadView('bdkd/sign/main');
        }

        public static function getExpressMsg($url , $options = array()) {
            //快递
            $options[CURLOPT_RETURNTRANSFER] = true;
            $options[CURLOPT_TIMEOUT] = 5;
            $options[CURLOPT_REFERER] =  'http://www.kuaidi100.com/';
            $options[CURLOPT_USERAGENT] = 'www.kuaidi100.com/';
            $ch = curl_init($url);
            curl_setopt_array($ch,$options);
            $html = curl_exec($ch);
            curl_close($ch);
            return $html;
        }


        public function getState($type,$postid) {
            $url = "http://www.kuaidi100.com/query?type=$type&postid=$postid&id=19&valicode=&temp=".mt_getrandmax();
            $express = json_decode(self::getExpressMsg($url) ,true);

//            if(isset($express['message']) && ($express['message'] === 'ok')) {
//                if($express['state']==3){
//                    return 1;
//                }else if($express['state']==2 || $express['state']==6){
//                    return 2;
//                }else{
//                    return 0;
//                }
//            }else{
//                return 2;
//            }

            if(isset($express['message']) && ($express['message'] === 'ok')) {
                if($express['state']==2 || $express['state']==6){
                    return 2;
                }else{
                    return $express['data'][0];
                }
            }else{
                return 2;
            }
        }


        /*
        * 分享
        */
        public function share(){

            Session::start();
            if($_SESSION['user.id']){
                $signPackage=Wxapi::getSignPackage();
                if($signPackage){
                    $this->loadView("bdkd/share/share",['signPackage'=>$signPackage]);
                }
                //var_dump($signPackage);exit;
            }
        }

        /*
         * 客服中心页面
         */
        public function customer(){
            $this->loadView("bdkd/customer/customer");
        }
        /*
         * 驾校
         */
        public function jiaxiao(){
            Session::start();
            if(isset($_SESSION['user.id'])){
                $a=[
                    'signPackage'=>Wxapi::getSignPackage()
                ];

                $this->loadView("bdkd/group/jiaxiao",['list'=>$a]);
            }

        }
        /*
         * 借款
         */
        public function jiek(){
            $this->loadView("bdkd/group/jiek");
        }
        /*
         * 理财
         */
        public function licai(){
            $this->loadView("bdkd/group/licai");
        }
        /*
         * 寄快递页面协议
         */
        public function jxy(){
            $this->loadView("bdkd/xy/jxy");
        }
        /*
         * 禁寄物品
         */
        public function jx(){
            $this->loadView("bdkd/xy/jx");
        }
        /*
         * 免责声明
         */
        public function sm(){
            $this->loadView("bdkd/xy/sm");
        }
        /*
         * 帮助中心
         */
        public function bz(){
            $this->loadView("bdkd/xy/bz");
        }

        /*
         * 便递员合作
         */
        public function bdh(){
            $this->loadView("bdkd/xy/bdh");
        }
        /*
         * 代取员帮助中心
         */
        public function dqx(){
            $this->loadView("bdkd/xy/dqx");
        }
        /*
         * dqy
         */
        public function dqy(){
            $this->loadView("bdkd/xy/dqy");
        }
        /*
         * yjb
         */
        public function yjb(){
            $this->loadView("bdkd/xy/yjb");
        }
        /*
         * yjy
         */
        public function yjy(){
            $this->loadView("bdkd/xy/yjy");
        }



        /*
        * 意见反馈页面展示
        */
        public function back()
        {
            Session::start();
            Db::connect();
            if (isset($_SESSION['user.id'])) {
                $data = user::get(["id" => $_SESSION['user.id']]);

                $this->loadView("bdkd/back/feedback",['data'=>$data]);
            }else{
                $this->loadView("bdkd/sign/main");
            }
        }
        /*
        * 意见美文页面展示
        */
        public function mback()
        {
            Session::start();
            Db::connect();
            if (isset($_SESSION['user.id'])) {
                $data = user::get(["id" => $_SESSION['user.id']]);

                $this->loadView("bdkd/back/mback",['data'=>$data]);
            }else{
                $this->loadView("bdkd/sign/main");
            }
        }
        //---意见反馈添加
        public function addback(){
            Session::start();
            Db::connect();
            //$_SESSION['user.id']=27;
            if(isset($_SESSION['user.id'])){
                if(empty(($_POST['context']))){
                    $this->writeJson(0,'请填写内容!');exit;
                }

                $feedback=new \C\mod\feedback();
                if(isset($_POST['type'])){
                    $feedback->set([
                        'user_id'=>$_SESSION['user.id'],
                        'context'=>$_POST['context'],
                        'type'=>1,
                        'time_add'=>$_SERVER['REQUEST_TIME']
                    ]);
                }else{
                  //  var_dump($_POST);
                    $feedback->set([
                        'user_id'=>$_SESSION['user.id'],
                        'context'=>$_POST['context'],
                        'time_add'=>$_SERVER['REQUEST_TIME']
                    ]);
                }

                if($feedback->create()){
                    //echo 33;exit;
                    $this->writeJson(1);exit;
                }else{
                   // echo 22;exit;
                    $this->writeJson(0,'提交失败!');exit;
                }
            }else
                $this->loadView("bdkd/sgin/main");
        }




        /*
         * 查询价格页面
         */
        public function price(){
            $this->loadView("bdkd/home/price");
        }
        /*
         * 查询时间页面
         */
        public function time(){
            $this->loadView("bdkd/home/time");
        }

        /*
         *微信公众号支付jsapi(取快递页面)
         */
        public function wxqpay(){
            Db::connect();
            Session::start();
            //($_SESSION);
            if(isset($_SESSION['user.id'])){
                $zhekou='';//从优惠券页面进来的时候是有折扣的
                $vid='';
                if(isset($_GET['zhekou'])){
                    $zhekou=$_GET['zhekou'];
                }
                if(isset($_GET['vid'])){
                    $vid=$_GET['vid'];
                }

                $data=[];
                $worker=[];
                if(!empty($_GET['id'])){
                    $data=order::get(['id'=>$_GET['id']]);
                    if($data){
                        $worker=workerd::get(['worker_id'=>$data->worker_id]);
                    }
                    //print_r($data->order_id);
                }
                $num=count($data);
                //var_dump($data);
                $this->loadView("bdkd/order/qpay",['list'=>$data,'worker'=>$worker,'num'=>$num,'zhekou'=>$zhekou,'vid'=>$vid]);
                //$data=order::getList(['user_id'=>$_SESSION['user.id'],'pay_type'=>0,'type'=>0,'state'=>1]);
            }
        }
        /*
         *微信公众号支付jsapi(物流托运页面)
         */
        public function wxtpay(){
            Db::connect();
            Session::start();
            //($_SESSION);
            if(isset($_SESSION['user.id'])){
                $zhekou='';//从优惠券页面进来的时候是有折扣的
                $vid='';
                if(isset($_GET['zhekou'])){
                    $zhekou=$_GET['zhekou'];
                }
                if(isset($_GET['vid'])){
                    $vid=$_GET['vid'];
                }

                $data=[];
                $worker=[];
                if(!empty($_GET['id'])){
                    $data=order::get(['id'=>$_GET['id']]);
                    if($data){
                        $worker=workerd::get(['worker_id'=>$data->worker_id]);
                    }

                    //print_r($data->order_id);
                }
                $num=count($data);

                $this->loadView("bdkd/order/tpay",['list'=>$data,'worker'=>$worker,'num'=>$num,'zhekou'=>$zhekou,'vid'=>$vid]);
            }
        }

        /*
         * 微信公众号支付jsapi(寄快递页面)
         */
        public function wxhpay() {
            Db::connect();
            Session::start();
            //var_dump($_SESSION);
            if(isset($_SESSION['user.id'])){

                $zhekou='';//从优惠券页面进来的时候是有折扣的
                $vid='';
                if(isset($_GET['zhekou'])){
                    $zhekou=$_GET['zhekou'];
                }
                if(isset($_GET['vid'])){
                    $vid=$_GET['vid'];
                }

                $data=[];
                $worker=[];
                if(!empty($_GET['id'])){
                    $data=order::get(['id'=>$_GET['id']]);
                    if($data){
                        $worker=workerd::get(['worker_id'=>$data->worker_id]);
                    }

                    //print_r($data->order_id);
                }
                $num=count($data);
//                $data=[];
//                $data=order::getList(['user_id'=>$_SESSION['user.id'],'pay_type'=>0,'type'=>1,'state'=>1]);
//
//                $num=count($data);
                $this->loadView("bdkd/order/jpay",['list'=>$data,'worker'=>$worker,'num'=>$num,'zhekou'=>$zhekou,'vid'=>$vid]);
            }

        }
        public function doPay(){
            Db::connect();
            Session::start();

            if(isset($_SESSION['user.id'])){
                // $this->writeJson(0,$_POST);exit;
//                if(empty($_POST['attach'])){
//                    $this->writeJson(0,'8');exit;
//                }
                $vid='';
                if(isset($_POST['money']) && !(empty($_POST['money']))){
                    $money=$_POST['money'];
                }else{
                    $this->writeJson(0,'4');exit;
                }
                if(empty($_POST['ids'])){
                    $this->writeJson(0,'5');exit;
                }
                if(isset($_POST['vid'])){
                    $vid=$_POST['vid'];
                }
                //var_dump($_POST);exit;
                $pay=order::get(['id'=>$_POST['ids'],'pay_type'=>1]);
               // var_dump($pay);//exit;
                if($pay){
                    $this->writeJson(0,'7');exit;
                }else{
                    $order_no =order::build_order_no();// 订单号
                    $user=user::get(['id'=>$_SESSION['user.id']]);//得到openid

                    //$this->writeJson(0,'3');exit;
                    $wxJsApi = Wxpay::createOrder([
                        'body' => '便递微信付款',
                        'attach' => $vid,
                        'out_trade_no' => $order_no,
//                        'total_fee' => $money*100,
                        'total_fee' => 1,
                        'notify_url' => HTTP_PATH . 'work/bpost/wxpayNotify',
                        'openid' => $user->wx_openid
                    ]);

                    if($wxJsApi){
                        //批量修改数据 事务处理
                        $order=order::get(['id'=>$_POST['ids']]);
                        $order->set([
                            'order_pid'=>$order_no
                        ]);
                        if($order->update()){
                            $this->writeJson(0,$wxJsApi);exit;//成功！
                        }else{
                            $this->writeJson(0,'3');exit;
                        }



//                    try {
//                        Db::beginTransaction();
//                        $idArr = explode(',',$_POST['ids']);
//                        for($i=0;$i<count($idArr);$i++)
//                        {
//                            $order=order::get(['id'=>$idArr[$i]]);
//                            $order->set([
//                                'order_pid'=>$order_no
//                            ]);
//                            $updata=$order->update();
//                        }
//                        Db::commit();
//                        $this->writeJson(0,$wxJsApi);exit;//成功！
//                    } catch (\Exception $e) {
//                        Db::rollBack(); // 执行失败，事务回滚
//                        $this->writeJson(0,'3');exit;
//                    }
                    }else{
                        $this->writeJson(0,'3');exit;
                    }
                }
            }
        }




        // --- 微信支付异步回调  修改订单状态---

        public function wxpayNotify() {

            Wxpay::callback();

        }


        /*
         * 快递员填写信息不符合 重新填写 修改状态
         */
        public function upState(){
            Session::start();
            if(isset($_SESSION['user.id'])){
                if(empty($_POST['id'])){
                    $this->writeJson(0,'缺少订单id！');exit;
                }
                if(empty($_POST['state'])){
                    $this->writeJson(0,'缺少订单状态！');exit;
                }

                $order=order::get(['id'=>$_POST['id']]);
                if($order->pay_type==1){
                    $this->writeJson(0,'您已完成支付,如有疑问请联系平台!');
                    exit;
                }
                $order->set([
                    'state'=>1
                ]);
                if($order->update()){
                    $this->writeJson(1);exit;
                }else{
                    $this->writeJson(0,'提交失败！');exit;
                }
            }
        }



        /*
		 * 用户删除订单(修改订单状态)
		 */
        public function delState(){
            Session::start();
            if(isset($_SESSION['user.id'])){
               // $this->writeJson(0,$_POST['id']);exit;
                if(empty($_POST['id'])){
                    $this->writeJson(0,'缺少订单参数!');exit;
                }
                $order=order::get(['id'=>$_POST['id']]);
                $order->set([
                    'state'=>4
                ]);
                if($order->update()){
                    $this->writeJson(1);exit;
                }else{
                    $this->writeJson(0,'删除失败!');exit;
                }
            }
        }

        //测试获取5公里内下单用户
        public function k(){
            $lat = '40.041169';
            $lng = '116.450961';
            $list=order::scope($lat,$lng);
            print_r($list);
        }




		// --- AJAX 接口 ---
		// --- 获取城市列表 ---

		public function getCitys() {

			$jcitys = [];
			$citys = city::getList(['available' => '1']);
			foreach ($citys as $city) {
				$jcitys[$city->id] = [
					'id' => $city->id,
					'name' => $city->name,
					'code' => $city->code,
					'parent' => $city->parent
				];
			}
			$this->writeJson(1, [
				'citys' => $jcitys
			]);

		}

		// --- 获取地址列表 ---

		public function getAddresss() {

			Session::start();

			// --- 判断用户是否登录 ---
			if(isset($_SESSION['user.id'])) {
				$jaddresss = [];
				$addresss = address::getList(['user_id'=> $_SESSION['user.id']]);
				foreach($addresss as $address){
					$jaddresss[]= [
						'id' => $address->id,
						'address_city'=> $address->address_city,
						'address_street' => $address->address_street,
						'preset' => $address->preset,
						'name' => $address->name,
						'phone' => $address->phone
					];
				}
				$this->writeJson(1,[
					'addresss' => $jaddresss
				]);
			} else
				$this->writeJson(0, '请您登录');

		}

		// --- 获取当前发件的价格 ---

		public function getPiecePrice() {

			// --- 判断依据 ---
			// --- 城市对城市可能会不同价格 ---
			// --- 企业月结\个人可能会不同价格 ---
			// --- 优惠券可能会不同价格 ---
			// --- 企业月结可能是百分比受城市对城市的价格的不同而变动 ---
			$price = orderPiece::getPrice($_POST['sCityId'], $_POST['rCityId']);

		}

		// --- 添加地址到数据库 ---

		public function addAddress() {

			Session::start();

			$address_city = trim($_POST['address_city']);
			$address_street = trim($_POST['address_street']);
			$address_residue = trim($_POST['address_residue']);
			// --- 判断是否登录 ---
			if(isset($_SESSION['user.id'])) {
				// --- 判断地址长度是否在数据库规定内 ---
				if(strlen($address_city)<=128 && strlen($address_street.$address_residue)<=255) {
					// ---判断是否存在城市层级 ---
					if ($citySub = city::get(['id' => $_POST['city_sub_id']])) {
						// --- 判断层级对应的城市是否正确 ---
						if ($citySub->parent == $_POST['city_id']) {
							$city_id = $citySub->is_city == 0 ? $citySub->parent : $citySub->id;
							$phone = trim($_POST['phone']);
							if(strlen($phone)>4) {
								if(substr($phone, 0, 1) != '1' || strlen($phone) == 11) {
									$name = trim($_POST['name']);
									if(strlen($name) > 2) {
//										if ($_POST['lat'] == '0' || $_POST['lng'] == '0') {
//											// --- 语义化分析 ---
//
//										}
										$arr=Ditu::curlGetWeb($address_city,$address_street.$address_residue);//根据地址获取经纬度
										$address = new \C\mod\address();
										$address->set([ // ---添加相关数据 ---
											'user_id' => $_SESSION['user.id'],
											'address_city' => $address_city,
											'address_street' => $address_street . $address_residue,
											'preset' => trim($_POST['preset']) == 1 ? 1 : 0,
											'name' => trim($_POST['name']),
											'phone' => $phone,
//											'lat' => $_POST['lat'] + 0,
//											'lng' => $_POST['lng'] + 0,
                                            'lat' => $arr['lat'],
											'lng' => $arr['lng'],
											'city_id' => $city_id,
											'city_sub_id' => 0
										]);
										$address->create();
										$this->writeJson(1);
									} else
										$this->writeJson(0, '请输入正确的姓名');
								} else
									$this->writeJson(0, '请输入正确电话号码');
							} else
								$this->writeJson(0, '请输入正确电话号码');
						} else
							$this->writeJson(0, '城市层级不正确');
					} else
						$this->writeJson(0, '城市不存在');
				} else
					$this->writeJson(0, '您输的地址过长');

			} else
				$this->writeJson(0, '请您登录');

		}

		// --- 添加订单/下单 ---

		public function addOrder() {

			Session::start();

			// --- 判断用户是否登录 ---
			if(isset($_SESSION['user.id'])) {

				if($sAddress = address::get(['id' => $_POST['sAddressId'], 'user_id' => $_SESSION['user.id']])) {
					if($rAddress = address::get(['id' => $_POST['rAddressId'], 'user_id' => $_SESSION['user.id']])) {
						if($user = user::get(['id' => $_SESSION['user.id']])) {
							// --- 计算保价费用 ---
							$pricePop = 0;
							$priceGoods = $_POST['priceGoods'] + 0;
							if ($priceGoods > 0) {
								if ($priceGoods <= 500)
									$pricePop = 1;
								else if ($priceGoods <= 1000)
									$pricePop = 2;
								else
									$pricePop = $priceGoods * 0.005;
							}
							$pricePop = round($pricePop);
							// --- 发件所需的费用 ---
							$pricePiece = 20;
							// --- 订单所属企业 ---
							$comId = '0';
							// --- 查看付款方式 ---
							$goOn = true;
							$msg = '';
							if($_POST['typePay'] == 0) {
								// --- 企业月结 ---
								// --- 判断是否是企业用户 ---
								// --- 计算单件的价格 ---
								if ($comPhone = comPhone::get(['phone' => $user->phone])) {
									$com = com::get(['id' => $comPhone->com_id]);
									$comId = $com->id;
									if($com->price_type == '0')
										$pricePiece = $com->price;
									else
										$pricePiece = $com->price * 20;
								} else {
									$goOn = false;
									$msg = '您不是企业月结客户,请联系业务员开通享受更多优惠';
								}
							} else if($_POST['typePay'] == 1) {
								// --- 线下先付 ---
							} else if($_POST['typePay'] == 2) {
								// --- 线下到付 ---
							} else if($_POST['typePay'] == 3) {
								// --- 微信支付 ---
							} else {
								$goOn = false;
								$msg = '付款方式不存在';
							}
							if($goOn) {
								// --- 查看优惠券,仅限非企业客户使用 ---
								$couponCode = '';
								$coupon = false;
								$_POST['couponCode'] = trim($_POST['couponCode']);
								if ($_POST['couponCode'] != '') {
									if($_POST['typePay'] != '0') {
										if ($coupon = coupon::get([
											'code' => $_POST['couponCode'],
											['user_id', 'in', ['0', $user->id]]
										])
										) {
											if ($coupon->time_end >= $_SERVER['REQUEST_TIME'] || $coupon->time_end == '0') {
												// --- 可以使用 ---
												if($coupon->type == '1') {
													// --- 仅仅是通行证 ---
												} else if($coupon->type == '2') {
													$pricePiece = $coupon->price;
												}
												$couponCode = $coupon->code;
											}
										}
									} else {
										$goOn = false;
										$msg = '企业月结用户无法享用普通优惠券';
									}
								}
								if($goOn) {
									// --- 创建订单 ---
									$order = new \C\mod\order();
									$order->set([
										'user_id' => $user->id,
										'count' => '1',
										'price' => $pricePop + $pricePiece,
										'time_add' => $_SERVER['REQUEST_TIME'],
										'type_pay' => $_POST['typePay'],
										'state_pay' => '0'
									]);
									do {
										$orderId = rand(100, 999) . $_SERVER['REQUEST_TIME'] . rand(100, 999);
										$order->set('order_id', $orderId);
									} while (!$order->create());
									// --- 创建件 ---
									$orderPiece = new orderPiece();
									$orderPiece->set([
										'order_id' => $order->order_id,
										'address_sender' => $sAddress->address_city . ' ' . $sAddress->address_street,
										'phone_sender' => $sAddress->phone,
										'name_sender' => $sAddress->name,
										'address_recipient' => $rAddress->address_city . ' ' . $rAddress->address_street,
										'phone_recipient' => $rAddress->phone,
										'name_recipient' => $rAddress->name,
										'time_add' => $_SERVER['REQUEST_TIME'],
										'price_goods' => $priceGoods,
										'price_pop' => $pricePop,
										'price' => $pricePop + $pricePiece,
										'type_pay' => $_POST['typePay'],
										'type_product' => '0',
										'state_pay' => '0',
										'state' => $_POST['typePay'] == '3' ? '5' : '0',
										'city_id_sender' => $sAddress->city_id,
										'city_id_recipient' => $rAddress->city_id,
										'lat_sender' => $sAddress->lat,
										'lng_sender' => $sAddress->lng,
										'lat_recipient' => $rAddress->lat,
										'lng_recipient' => $rAddress->lng,
										'user_id' => $user->id,
										'coupon_code' => $couponCode,
										'state_in' => $_POST['typePay'] == '3' ? '14' : '0',
										'com_id' => $comId
									]);
									$orderPiece->create();
									// --- 线上支付 ---
									if($_POST['typePay'] == '3') {

										// --- 微信支付 ---
										if($user->wx_openid != '') {
											$wxJsApi = Wxpay::createOrder([
												'body' => '线上微信付款',
												'attach' => '',
												'out_trade_no' => $order->order_id,
												'total_fee' => $pricePop + $pricePiece,
												'notify_url' => HTTP_PATH . 'mobi/bpost/wxpayNotify',
												'openid' => $user->wx_openid
											]);

											// --- 要 decode 一下否则是个字符串而不是 json 对象就呵呵哒了 ---
											$this->json['wxJsApi'] = $wxJsApi;
											$this->writeJson(1);
											
										} else
											$this->writeJson(0, '仅微信支持微信支付');
									} else
										$this->writeJson(1);
								} else
									$this->writeJson(0, $msg);
							} else
								$this->writeJson(0, $msg);
						} else
							$this->writeJson(0, '用户不存在');
					} else
						$this->writeJson(0, '地址不存在');
				} else
					$this->writeJson(0, '地址不存在');

			} else
				$this->writeJson(0, '请您登录');
		}
		

		// --- 获取企业支付传导 ---
		public function getComPrice() {

			Session::start();

			// --- 判断用户是否登录 ---
			if(isset($_SESSION['user.id'])) {
				$user = user::get(['id' => $_SESSION['user.id']]);
				if ($comPhone = comPhone::get(['phone' => $user->phone])) {
					$com = com::get(['id' => $comPhone->com_id]);
					if ($com->price_type == '0') {
						$comPrice = $com->price;
					} else if($com->price == '1') {
						$comPrice = $com->price * 20;
					} else {
						$comPrice = 20;
					}
					$this->writeJson(1, [
						'comPrice' => $comPrice
					]);
				} else {
					$this->writeJson(0, '您不是企业客户,联系业务员开通享受更多优惠');
				}
			} else
				$this->writeJson(0, '请您登录');

		}

		// --- 编辑地址 ---
		public function updateAddress(){

			Session::start();
			$address_city = trim($_POST['address_city']);
			$address_street = trim($_POST['address_street']);
			// --- 判断是否登录 ---
			if(isset($_SESSION['user.id'])) {
				// --- 判断地址长度是否在数据库规定内 ---
				if(strlen($address_city)<=128 && strlen($address_street)<=255) {
					// ---判断是否存在城市层级 ---
					if ($citySub = city::get(['id' => $_POST['city_sub_id']])) {
						// ---判断层级对应的城市是否正确 ---
						if ($citySub->parent == $_POST['city_id']) {
							$address = address::get(['id' => $citySub->id]);
							$address->set([ // ---添加相关数据 ---
								'user_id' => $_SESSION['user.id'],
								'address_city' => $address_city,
								'address_street' => $address_street,
								'preset' => trim($_POST['preset']) == 1 ? 1 : 0,
								'name' => trim($_POST['name']),
								'phone' => trim($_POST['phone']),
								'lat' => $_POST['lat']+0,
								'lng' => $_POST['lng']+0,
								'city_id' => $citySub->parent,
								'city_sub_id' => $citySub->id
							]);

							$address->update();
							$this->writeJson(1);
						} else
							$this->writeJson(0, '城市层级不正确');
					} else
						$this->writeJson(0, '城市不存在');
				} else
					$this->writeJson(0, '您输的地址过长');
			} else
				$this->writeJson(0, '请您登录');

		}

		// --- 删除地址 ---
		public function deleteAddress() {

			Session::start();

			// --- 判断客户是否登录 ---
			if(isset($_SESSION['user.id'])) {

				// --- 判断当前客户是否添加过此地址 ---
				if($address = address::get(['id' => trim($_POST['id']), 'user_id' => $_SESSION['user.id']])) {

					// --- 判断客户是否删除成功 ---
					if($address->remove()) {
						$this->writeJson(1);
					} else
						$this->writeJson(0, '删除失败');
				} else
					$this->writeJson(0, '没有记录');
			}
			else
				$this->writeJson(0, '请您登录');
		}

	}

}

